package com.carey.swift.dev.mapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SwiftHandlerMethod {


    private static final String VIEWPATH="/";
    private static final String VIEWTYPE=".html";

    /**
     * 请求分发
     * @param request
     * @param response
     */
    public void processRequest(HttpServletRequest request,HttpServletResponse response){

        String uri=request.getRequestURI();
        ControllerModel controllerModel= StaticCache.getControllerModel(uri);
        if(null!=controllerModel) {
            HttpMethod httpMethod = controllerModel.getHttpMethod();
            String method = request.getMethod();

            if (httpMethod == HttpMethod.ALL) {
                try {
                    Parameter[] parameters =
                            controllerModel.getMethod().getParameters();
                    List<Parameter> parameterList = Arrays.asList(parameters);
                    List<Object> parameterObj = new ArrayList<>();
                    for (Parameter parameter : parameterList) {
                        if (parameter.getType().getTypeName()
                                .equals(HttpServletRequest.class.getTypeName())) {
                            parameterObj.add(request);
                        }
                        if (parameter.getType().getTypeName()
                                .equals(HttpServletResponse.class.getTypeName())) {
                            parameterObj.add(response);
                        }
                    }
                    Object result = controllerModel.getMethod()
                            .invoke(controllerModel.getObject(), parameterObj.toArray());

                    if (result instanceof String) {
                        StringBuffer buffer = new StringBuffer();
                        buffer.append(VIEWPATH);
                        buffer.append(result);
                        buffer.append(VIEWTYPE);
                       request.getRequestDispatcher(buffer.toString()).forward(request,response);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (ServletException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
